package com.dormitory.management.system.DAO;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dormitory.management.system.entity.CostExcel;
import com.dormitory.management.system.entity.Email;
import com.dormitory.management.system.entity.Room;
import com.dormitory.management.system.mapper.RoomMapper;
import com.dormitory.management.system.mapper.StudentMapper;
import com.dormitory.management.system.req.CostSaveReq;
import com.dormitory.management.system.resp.StuAndHouResp;
import com.dormitory.management.system.service.CostService;
import com.dormitory.management.system.service.UserService;
import com.dormitory.management.system.utils.EmailUtil;

import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Repository
public class UpLoadCostExcelFileDao {

    @Autowired
    @Lazy
    private CostService costService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    public void save(List<CostExcel> list,String username) {
        CostSaveReq req = new CostSaveReq();
        for(int i=0 ; i <list.size();i++){
            req.setCostTotal(list.get(i).getCostTotal());
            req.setCostWater(list.get(i).getCostWater());
            req.setCostElectric(list.get(i).getCostElectric());
            req.setRoomId(list.get(i).getRoomId());
            req.setQuantityElectric(list.get(i).getQuantityElectric());
            req.setCostWater(list.get(i).getQuantityWater());
            costService.save(req);
            //发送邮件
            sendMail(list.get(i).getRoomId(),username);
        }
    }

    //宿管导入水电报表后发送
    private void sendMail(Long id,String userId){
        Room leaderRoom = roomMapper.selectById(id);
        StuAndHouResp studentInfo = studentMapper.getStudentInfo(new QueryWrapper<StuAndHouResp>().eq("s.stu_id", leaderRoom.getLeaderId()));
        StuAndHouResp userInfo = userService.getUserInfo(userId);
        Email email = new Email(userInfo.getPhone(),userInfo.getName(),userService.getRoleKey(userId));
        String emailHou = studentInfo.getEmail();
        String name = studentInfo.getName();
        String room=studentInfo.getLiving()+"-"+studentInfo.getBuilding()+"-"+studentInfo.getRoom();
        String content = email.remindToPay(name, room);
        String subject="当月水电账单已发布请查收";
        String filePath=null;
        redisTemplate.opsForValue().set(emailHou+"***"+subject+"***"+content+"***"+filePath,"dxc",10,TimeUnit.SECONDS);
    }
}